import * as types from '../types'
import axios from 'axios'

const state = {
  comments: [],
  total: 0
}

const getters = {
  totalComments: state => state.total,
  comments: state => state.comments
}

let setRemoved = item => {
  item.removed = false
  if (item.comments && item.comments.length) {
    for (var index = 0; index < item.comments.length; index++) {
      setRemoved(item.comments[index])
    }
  }
}

const mutations = {
  [types.COMMENTS_LOADED](state, data) {
    for (var index = 0; index < data.comments.length; index++) {
      setRemoved(data.comments[index])
    }
    state.comments = data.comments
    state.total = data.total
  },
  [types.COMMENT_SAVED](state, data) {
    data.removed = false
    if (data.rootId) {
      var item = state.comments.find(comment => comment.id === data.rootId)
      if (!item) return
      item.comments = item.comments || []
      item.comments.push(data)
      item.replied++
    } else {
      state.comments.unshift(data)
      state.total++
    }
  }
}

const actions = {
  async loadComments({
    commit
  }, query) {
    const response = await axios.get('/vts/comment/list', {
      params: query
    })
    if (response.status === 200) commit(types.COMMENTS_LOADED, response.data)
  },
  async saveComment({
    commit
  }, data) {
    const response = await axios.post('/vts/comment/add', data.form)
    if (response.status === 200) {
      if (response.data.saved) commit(types.COMMENT_SAVED, response.data.data)
      data.callback && data.callback(response.data)
    }
  },
  async removeComment({
    commit
  }, data) {
    const response = await axios.post('/vts/comment/remove', {
      id: data.id
    })
    if (response.data.removed) data.callback()
  }
}

export default {
  state,
  mutations,
  actions,
  getters
}
